// src/components/TopicPostDetail.js - 话题帖子详情组件

import React, { useState, useEffect } from 'react';
import {
  Modal, Typography, Card, Button, Space, Tag, Avatar, List,
  Input, Form, message, Divider, Popconfirm, Dropdown, Menu,
  Tooltip, Badge, Pagination, Empty, Spin
} from 'antd';
import {
  UserOutlined, LikeOutlined, CommentOutlined, EyeOutlined,
  DeleteOutlined, PushpinOutlined, MoreOutlined, SendOutlined,
  ClockCircleOutlined, EditOutlined, CrownOutlined, TeamOutlined
} from '@ant-design/icons';
import { topics, comments } from '../services';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

const TopicPostDetail = ({
  visible,
  onClose,
  postId,
  topicId,
  currentUser,
  topic,
  onPostUpdate
}) => {
  const [post, setPost] = useState(null);
  const [postComments, setPostComments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [commentsLoading, setCommentsLoading] = useState(false);
  const [newComment, setNewComment] = useState('');
  const [commentForm] = Form.useForm();
  const [isLiked, setIsLiked] = useState(false);
  const [likedComments, setLikedComments] = useState(new Set()); // 追踪已点赞的评论
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  useEffect(() => {
    if (visible && postId) {
      loadPostDetail();
      loadComments();
      // 检查用户是否已点赞此帖子
      checkPostLikeStatus();
    }
  }, [visible, postId]);

  // 检查帖子点赞状态
  const checkPostLikeStatus = () => {
    if (!currentUser || !post) {
      setIsLiked(false);
      return;
    }

    // 检查本地存储中的点赞状态
    const likesKey = `starrypt_post_${post.postId || post.id}_likes`;
    const likesStr = localStorage.getItem(likesKey);
    let likes = likesStr ? JSON.parse(likesStr) : [];

    const hasLiked = likes.some(like => like.username === currentUser.username);
    setIsLiked(hasLiked);
    console.log('帖子点赞状态检查:', { postId: post.postId || post.id, hasLiked, likesCount: likes.length });
  };

  // 加载帖子详情
  const loadPostDetail = async () => {
    try {
      setLoading(true);
      const response = await topics.getTopicPostDetail(topicId, postId);
      if (response.success) {
        const postData = response.data;
        setPost(postData);
        setIsLiked(postData.liked || false); // 设置点赞状态
      }
    } catch (error) {
      console.error('加载帖子详情失败:', error);
      message.error('加载帖子详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载评论
  const loadComments = async () => {
    if (!post?.postId) return;

    try {
      setCommentsLoading(true);
      const response = await comments.getPostComments(post.postId, {
        page: pagination.current,
        limit: pagination.pageSize
      });

      if (response.success) {
        const comments = response.data.replies || [];
        setPostComments(comments);
        setPagination(prev => ({
          ...prev,
          total: response.data.pagination?.total || 0
        }));

        // 更新评论点赞状态（保留现有状态）
        if (currentUser) {
          const liked = new Set(likedComments); // 保留现有状态
          comments.forEach(comment => {
            const likesKey = `starrypt_comment_${comment.commentId}_likes`;
            const likesStr = localStorage.getItem(likesKey);
            const likes = likesStr ? JSON.parse(likesStr) : [];
            if (likes.some(like => like.username === currentUser.username)) {
              liked.add(comment.commentId);
            } else {
              liked.delete(comment.commentId); // 如果不在localStorage中，从Set中移除
            }
          });
          setLikedComments(liked);
          console.log('更新评论点赞状态:', Array.from(liked));
        }
      }
    } catch (error) {
      console.error('加载评论失败:', error);
      message.error('加载评论失败');
    } finally {
      setCommentsLoading(false);
    }
  };

  // 发布评论
  const handleAddComment = async () => {
    if (!newComment.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    try {
      setLoading(true);
      const response = await comments.addComment({
        postId: post.postId,
        content: newComment.trim()
      });

      if (response.success) {
        message.success('评论发布成功');
        setNewComment('');
        loadComments(); // 重新加载评论
      } else {
        message.error(response.message || '评论发布失败');
      }
    } catch (error) {
      console.error('发布评论失败:', error);
      message.error('发布评论失败');
    } finally {
      setLoading(false);
    }
  };

  // 删除评论
  const handleDeleteComment = async (commentId) => {
    try {
      const response = await comments.deleteComment(commentId);
      if (response.success) {
        message.success('评论删除成功');
        loadComments();
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除评论失败:', error);
      message.error('删除评论失败');
    }
  };

  // 点赞评论
  const handleLikeComment = async (commentId) => {
    try {
      const response = await comments.likeComment(commentId);
      if (response.success) {
        // 立即更新评论点赞状态
        const newLikedComments = new Set(likedComments);
        if (newLikedComments.has(commentId)) {
          newLikedComments.delete(commentId);
          message.success('取消点赞成功');
        } else {
          newLikedComments.add(commentId);
          message.success('点赞成功');
        }
        setLikedComments(newLikedComments);

        // 重新加载评论以更新点赞数
        loadComments();
      } else {
        message.error(response.message || '点赞失败');
      }
    } catch (error) {
      console.error('点赞评论失败:', error);
      message.error('点赞评论失败');
    }
  };

  // 点赞帖子
  const handleLike = async () => {
    try {
      const response = await topics.likeTopicPost(postId);
      if (response.success) {
        console.log('帖子详情页点赞操作响应:', response.data);

        // 立即更新UI状态
        setIsLiked(!isLiked);

        // 更新帖子数据
        setPost(prev => {
          const newLikes = response.data.likes !== undefined ? response.data.likes : prev.likes;
          console.log(`帖子详情页 ${postId} 点赞数更新: ${prev.likes} -> ${newLikes}`);
          return {
            ...prev,
            likes: newLikes,
            liked: !prev.liked
          };
        });

        // 通知父组件更新
        if (onPostUpdate) {
          onPostUpdate();
        }

        message.success(isLiked ? '取消点赞成功' : '点赞成功');
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      message.error('点赞操作失败');
    }
  };

  // 置顶/取消置顶帖子
  const handlePinPost = async () => {
    try {
      const response = await topics.pinTopicPost(topicId, post.postId);
      if (response.success) {
        message.success(response.message || '置顶操作成功');
        onPostUpdate(); // 通知父组件更新
      } else {
        message.error(response.message || '置顶操作失败');
      }
    } catch (error) {
      console.error('置顶操作失败:', error);
      message.error('置顶操作失败');
    }
  };

  // 删除帖子
  const handleDeletePost = async () => {
    try {
      const response = await topics.deleteTopicPost(topicId, post.postId);
      if (response.success) {
        message.success('帖子删除成功');
        onClose(); // 关闭详情页
        onPostUpdate(); // 通知父组件更新
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除帖子失败:', error);
      message.error('删除帖子失败');
    }
  };

  // 检查权限
  const canManagePost = () => {
    if (!currentUser || !post) return false;
    return (
      currentUser.username === post.author ||
      currentUser.username === topic?.creator ||
      currentUser.role === 'admin' ||
      (topic?.moderators && topic.moderators.includes(currentUser.username))
    );
  };

  const canDeleteComment = (comment) => {
    if (!currentUser) return false;
    return (
      currentUser.username === comment.author ||
      currentUser.role === 'admin' ||
      canManagePost()
    );
  };

  const formatTime = (timeString) => {
    const time = new Date(timeString);
    const now = new Date();
    const diffInSeconds = Math.floor((now - time) / 1000);

    if (diffInSeconds < 60) return '刚刚';
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`;
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`;
    if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)}天前`;

    return time.toLocaleDateString();
  };

  // 管理员菜单
  const adminMenu = (
    <Menu>
      <Menu.Item
        key="pin"
        icon={<PushpinOutlined />}
        onClick={handlePinPost}
      >
        {post?.isPinned ? '取消置顶' : '置顶帖子'}
      </Menu.Item>
      <Menu.Item
        key="delete"
        icon={<DeleteOutlined />}
        danger
        onClick={handleDeletePost}
      >
        删除帖子
      </Menu.Item>
    </Menu>
  );

  if (!post) return null;

  return (
    <Modal
      title="帖子详情"
      open={visible}
      onCancel={onClose}
      footer={null}
      width={800}
      style={{ maxHeight: '90vh' }}
      styles={{ body: { maxHeight: '70vh', overflow: 'auto' } }}
    >
      <Card>
        {/* 帖子头部 */}
        <div style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div style={{ flex: 1 }}>
              <Space>
                {post.isPinned && (
                  <Badge count="置顶" style={{ backgroundColor: '#722ed1' }} />
                )}
                <Title level={4} style={{ margin: 0 }}>
                  {post.title}
                </Title>
              </Space>
            </div>
            {canManagePost() && (
              <Dropdown overlay={adminMenu} trigger={['click']}>
                <Button type="text" icon={<MoreOutlined />} />
              </Dropdown>
            )}
          </div>

          <Space style={{ marginTop: 8 }}>
            <Avatar size="small" icon={<UserOutlined />} />
            <Text strong>{post.author}</Text>
            <Text type="secondary">
              <ClockCircleOutlined /> {formatTime(post.createTime)}
            </Text>
            {post.tags && (
              (typeof post.tags === 'string' ? post.tags.split(',') : post.tags).map(tag => (
                <Tag key={tag} size="small">{tag.trim()}</Tag>
              ))
            )}
          </Space>
        </div>

        {/* 帖子内容 */}
        <Paragraph style={{ fontSize: 16, lineHeight: 1.6 }}>
          {post.content}
        </Paragraph>

        {/* 帖子操作 */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 0', borderTop: '1px solid #f0f0f0' }}>
          <Space>
            <Button
              type={isLiked ? "primary" : "text"}
              icon={<LikeOutlined />}
              onClick={handleLike}
              className={isLiked ? 'liked' : ''}
            >
              {post.likes || 0}
            </Button>
            <Button type="text" icon={<CommentOutlined />}>
              {postComments.length}
            </Button>
            <Button type="text" icon={<EyeOutlined />}>
              {post.views || 0}
            </Button>
          </Space>
        </div>

        <Divider>评论 ({pagination.total})</Divider>

        {/* 发布评论 */}
        <div style={{ marginBottom: 16 }}>
          <TextArea
            rows={3}
            placeholder="发表你的看法..."
            value={newComment}
            onChange={(e) => setNewComment(e.target.value)}
            maxLength={1000}
            showCount
          />
          <div style={{ marginTop: 8, textAlign: 'right' }}>
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={handleAddComment}
              loading={loading}
              disabled={!newComment.trim()}
            >
              发布评论
            </Button>
          </div>
        </div>

        {/* 评论列表 */}
        <Spin spinning={commentsLoading}>
          {postComments.length > 0 ? (
            <>
              <List
                dataSource={postComments}
                renderItem={(comment) => (
                  <List.Item
                    key={comment.commentId}
                    actions={[
                      <Button
                        type={likedComments.has(comment.commentId) ? "primary" : "text"}
                        size="small"
                        icon={<LikeOutlined />}
                        className={likedComments.has(comment.commentId) ? 'liked' : ''}
                        onClick={() => handleLikeComment(comment.commentId)}
                      >
                        {comment.likes || 0}
                      </Button>,
                      canDeleteComment(comment) && (
                        <Popconfirm
                          title="确定要删除这条评论吗？"
                          onConfirm={() => handleDeleteComment(comment.commentId)}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button
                            type="text"
                            size="small"
                            icon={<DeleteOutlined />}
                            danger
                          >
                            删除
                          </Button>
                        </Popconfirm>
                      )
                    ].filter(Boolean)}
                  >
                    <List.Item.Meta
                      avatar={<Avatar size="small" icon={<UserOutlined />} />}
                      title={
                        <Space>
                          <Text strong>{comment.author}</Text>
                          <Text type="secondary" style={{ fontSize: 12 }}>
                            {formatTime(comment.createTime)}
                          </Text>
                        </Space>
                      }
                      description={comment.content}
                    />
                  </List.Item>
                )}
              />

              {pagination.total > pagination.pageSize && (
                <div style={{ textAlign: 'center', marginTop: 16 }}>
                  <Pagination
                    current={pagination.current}
                    pageSize={pagination.pageSize}
                    total={pagination.total}
                    onChange={(page) => {
                      setPagination(prev => ({ ...prev, current: page }));
                      loadComments();
                    }}
                    showSizeChanger={false}
                    showQuickJumper
                    showTotal={(total, range) => `${range[0]}-${range[1]} 共 ${total} 条评论`}
                  />
                </div>
              )}
            </>
          ) : (
            <Empty description="暂无评论，快来发表第一条评论吧！" />
          )}
        </Spin>
      </Card>
    </Modal>
  );
};

export default TopicPostDetail; 